package com.scalable.io.bio;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketAddress;

public class ServerHandler implements Runnable {

    private final Socket socket;

    public ServerHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        SocketAddress remoteSocketAddress = socket.getRemoteSocketAddress();
        System.out.println("connection seccuss " + remoteSocketAddress);
        try {
            inputStream = socket.getInputStream();
            outputStream = socket.getOutputStream();
            byte[] bytes = new byte[1024];
            while (inputStream.read(bytes) > 0) {
                System.out.println("recv from " + remoteSocketAddress + ": " + new String(bytes));

                outputStream.write("OK\n".getBytes());
                System.out.println("send success " + remoteSocketAddress);
            }
            System.out.println("connection close " + remoteSocketAddress);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (outputStream != null) outputStream.close();
                if (inputStream != null) inputStream.close();
                if (socket != null) socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
